package com.ssm.basis.web.controller;

import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.ssm.basis.web.util.RequestUtil.getSessionId;
import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME;

@Hidden
@RestController
@Tag(name = "session")
@RequiredArgsConstructor
@RequestMapping("session")
public class SessionController {
    final FindByIndexNameSessionRepository<? extends Session> sessionRepository;

    @DeleteMapping
    @Operation(summary = "删除当前用户所有 session")
    public void delete(HttpServletRequest request, @AuthenticationPrincipal User user) {
        // 当前用户 session id
        getSessionId(request);
        // 当前用户所有 session
        Map<String, ? extends Session> sessionMap = get(user);
        sessionMap.keySet().forEach(sessionRepository::deleteById);
    }

    @GetMapping
    @Operation(summary = "获取当前用户所有 session 信息(登录多次)")
    public Map<String, ? extends Session> get(@Parameter(hidden = true) @AuthenticationPrincipal User user) {
        return sessionRepository.findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, user.getUsername());
    }
}
